package com.elitesland.org.rest;

import com.elitesland.core.base.ApiCode;
import com.elitesland.core.base.ApiResult;
import com.elitesland.core.base.PagingVO;
import com.elitesland.org.param.OrgOuQParam;
import com.elitesland.org.param.OrgOuSaveParam;
import com.elitesland.org.service.OrgOuService;
import com.elitesland.org.vo.OrgOuVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/org/ous")
@Api(value = "组织结构", tags = {"公司管理"})
public class OrgOuController {

    private OrgOuService orgOuService;

    @Autowired
    public void setOrgOuService(OrgOuService orgOuService) {
        this.orgOuService = orgOuService;
    }

    @GetMapping("/bytree/{pid}")
    @ApiOperation("根据父公司ID列出子公司数据的树形结构")
    public ApiResult<List<OrgOuVO>> listTree(@PathVariable Long pid) {
        val entities = orgOuService.listTreeByPId(pid);
        return ApiResult.ok(entities);
    }

    @PostMapping("/q/{pid}")
    @ApiOperation("查询父公司下的子公司")
    public ApiResult<PagingVO<OrgOuVO>> searchByPId(
            @PathVariable Long pid,
            @RequestBody OrgOuQParam param) {
        val ret = orgOuService.searchByPId(pid, param);
        return ApiResult.ok(ret);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据记录ID返回公司信息")
    public ApiResult<OrgOuVO> oneById(@PathVariable("id") Long id) {
        return orgOuService.oneById(id).map(ApiResult::ok)
                .orElse(ApiResult.fail(ApiCode.NOT_FOUND));
    }

    @PostMapping
    @ApiOperation("创建公司")
    public ApiResult<Long> create(@RequestBody OrgOuSaveParam entity) {
        val id = orgOuService.create(entity);
        return ApiResult.ok(id);
    }

    @PutMapping
    @ApiOperation("更新公司信息")
    public ApiResult<Object> update(@RequestBody OrgOuSaveParam entity) {
        orgOuService.update(entity);
        return ApiResult.ok();
    }

    @PutMapping("/sort")
    @ApiOperation("子子公司重排序")
    public ApiResult<Object> updateSort(@RequestBody List<OrgOuVO> entities) {
        orgOuService.updateSort(entities);
        return ApiResult.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除当前公司，及其下属的所有公司")
    public ApiResult<Object> removeById(@PathVariable Long id) {
        orgOuService.removeById(id);
        return ApiResult.ok();
    }
}
